package com.tepth.remote.control.delegate.attendance;

import android.annotation.SuppressLint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.tepth.remote.control.R;
import com.tepth.remote.control.R2;
import com.tepth.remote.control.base.bean.Config;
import com.tepth.remote.control.base.bean.Fences;
import com.tepth.remote.control.base.bean.Project;
import com.tepth.remote.control.base.config.ApiDictionary;
import com.tepth.remote.control.base.config.SpKey;
import com.tepth.remote.control.base.convert.ObjectConverter;
import com.tepth.remote.control.base.map.overlay.DrawOverlay;
import com.tepth.remote.control.base.map.overlay.MarkerOverlay;
import com.tepth.remote.control.base.mvp.BaseMvpDelegate;
import com.tepth.remote.control.manager.ConfigManager;
import com.tepth.remote.core.net.callback.IError;
import com.tepth.remote.core.net.callback.ISuccess;
import com.tepth.remote.core.net.retrofit.RxRetrofitClient;
import com.tepth.remote.core.utils.resources.ResourcesUtil;
import com.tepth.remote.ui.alert.DialogLoader;
import com.tepth.remote.ui.alert.IDialogClickListener;
import com.tepth.remote.ui.recycler.MultipleFields;
import com.tepth.remote.ui.recycler.MultipleItemEntity;
import com.tepth.remote.ui.recycler.MultipleRecyclerAdapter;
import com.tepth.remote.ui.recycler.MultipleRecyclerClickListener;
import com.tepth.remote.ui.recycler.grid.GridItemType;

import java.util.ArrayList;
import java.util.WeakHashMap;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Description:
 *
 * @author Hequn.Lee
 * @date 2018/11/20
 */
public class AttendanceDelegate extends BaseMvpDelegate<AttendancePresenter> implements AttendanceContract.View, MultipleRecyclerClickListener {

    public static final String CENTER = "center";

    @BindView(R2.id.rv_project)
    RecyclerView recyclerView = null;
    @BindView(R2.id.linear_fences_layout)
    LinearLayoutCompat linearFencesLayout = null;
    @BindView(R2.id.mapView)
    MapView mMapView = null;
    @BindView(R2.id.linear_fences_bottom)
    LinearLayoutCompat linearLayoutBottom = null;
    @BindView(R2.id.text_attendance_rule)
    AppCompatTextView textAttendanceRule = null;
    @BindView(R2.id.text_attendance_count)
    AppCompatTextView textAttendanceCount = null;

    /**
     * 百度地图控件
     */
    private BaiduMap baiduMap;
    private MultipleRecyclerAdapter mAdapter = null;
    private int lastProjectIndex = -1;
    private DialogLoader mDialogLoader = null;

    public static AttendanceDelegate create(LatLng latLng) {
        final AttendanceDelegate contentDelegate = new AttendanceDelegate();
        final Bundle bundle = new Bundle();
        bundle.putParcelable(CENTER, latLng);
        contentDelegate.setArguments(bundle);
        return contentDelegate;
    }

    @OnClick(R2.id.button_refresh)
    void onClick() {
        mDialogLoader.showProgressDialog(false, "正在加载", "");
        RxRetrofitClient.builder()
                .url(ApiDictionary.API_GET_CONFIG)
                .params("Imei", ConfigManager.getInstance().getPhoneId())
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(Object value) {
                        mDialogLoader.clearDialog();
                        final Config config = new ObjectConverter<Config>().convert(JSON.toJSONString(value),
                                new TypeReference<Config>() {
                                });
                        ConfigManager.getInstance()
                                .setRealName(config.getRealName())
                                .setUid(config.getUid())
                                .setPhoneId(config.getPhoneId())
                                .setIsBm(config.getIsBm())
                                .setIsZj(config.getIsZj())
                                .setProjects(config.getProjects());
                        final ArrayList<Project> allData = config.getProjects();
                        AttendanceDataConvert convert = new AttendanceDataConvert();
                        mAdapter.setNewData(convert.setData(convert.convertProjectToObject(allData)).convert());
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mDialogLoader.clearDialog();
                    }
                })
                .builder()
                .get();
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_attendance;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mDialogLoader = new DialogLoader(getProxyActivity());
        final Bundle bundle = getArguments();
        initRecyclerView();
        if (bundle != null) {
            final LatLng latLng = bundle.getParcelable(CENTER);
            if (latLng != null) {
                initMap(latLng);
            } else {
                initMap(new LatLng(29.566483, 106.564186));
            }
        } else {
            initMap(new LatLng(29.566483, 106.564186));
        }
    }

    private void initRecyclerView() {
        final ArrayList<Project> allData = ConfigManager.getInstance().getProjects();
        final AttendanceDataConvert converter = new AttendanceDataConvert();
        mAdapter = MultipleRecyclerAdapter.create(converter.setData(
                converter.convertProjectToObject(allData)).convert(), this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        //3.给GridLayoutManager设置滑动的方向
        linearLayoutManager.setOrientation(GridLayoutManager.HORIZONTAL);
        //4.为recyclerView设置布局管理器
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(mAdapter);
        //一个一个的滑动（完全ViewPager效果）
        final PagerSnapHelper snapHelper = new PagerSnapHelper();
        //其他都与RecyclerView一样，只需要绑定下就行
        snapHelper.attachToRecyclerView(recyclerView);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                // 项目数量大于1并且当停止滑动时
                if (mAdapter.getItemCount() > 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                    baiduMap.clear();
                    if (linearFencesLayout != null) {
                        if (linearFencesLayout.getChildCount() > 0) {
                            linearFencesLayout.removeAllViews();
                        }
                        linearFencesLayout.setVisibility(View.GONE);
                    }
                    if (linearLayoutBottom != null) {
                        linearLayoutBottom.setVisibility(View.GONE);
                    }
                    if (lastProjectIndex >= 0) {
                        final MultipleItemEntity entity = mAdapter.getItem(lastProjectIndex);
                        if (entity != null) {
                            entity.setField(MultipleFields.IS_PULL, false);
                            mAdapter.setData(lastProjectIndex, entity);
                        }
                        lastProjectIndex = -1;
                    }
                }
            }
        });
    }

    private void initMap(LatLng latLng) {
        baiduMap = mMapView.getMap();
        // 开启定位图层
        baiduMap.setMyLocationEnabled(false);
        // 隐藏缩放控件
        mMapView.showScaleControl(false);
        // 隐藏比例尺控件
        mMapView.showZoomControls(false);
        baiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(latLng, 15.0f));
    }

    @Override
    public void onclickListener(MultipleFields type, int position) {
        switch (type) {
            case BACK:
                pop();
                break;
            case PULL:
                if (linearFencesLayout != null) {
                    linearFencesLayout.removeAllViews();
                }
                final MultipleItemEntity entity = mAdapter.getItem(position);
                if (entity != null) {
                    final boolean isPull = entity.getField(MultipleFields.IS_PULL);
                    if (isPull) {
                        if (linearLayoutBottom != null) {
                            linearLayoutBottom.setVisibility(View.GONE);
                        }
                        if (linearFencesLayout != null) {
                            linearFencesLayout.setVisibility(View.GONE);
                        }
                        lastProjectIndex = -1;
                    } else {
                        lastProjectIndex = position;
                        if (linearFencesLayout != null) {
                            linearFencesLayout.setVisibility(View.VISIBLE);
                            final Project project = entity.getField(MultipleFields.PROJECT);
                            final ArrayList<Fences> fences = project.getUserElecFences();
                            final int size = fences.size();
                            for (int i = 0; i < size; i++) {
                                linearFencesLayout.addView(getTextView(fences.get(i), i));
                            }
                        }
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onLoadRecyclerError(String msg) {

    }

    @Override
    public void onclickViewPagerListener(GridItemType type) {
    }

    private AppCompatTextView getTextView(final Fences fences, final int fencePosition) {
        final AppCompatTextView textView = new AppCompatTextView(getProxyActivity());
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        textView.setGravity(Gravity.CENTER);
        textView.setTextColor(ResourcesUtil.getColorFromResources(getContext(), R.color.text_fences));
        textView.setTextSize(20);
        textView.setSingleLine(true);
        textView.setBackgroundResource(R.drawable.text_fences);
        textView.setText(fences.getEFB_Name());
        textView.setTypeface(Typeface.DEFAULT);
        textView.setPadding(0, 10, 0, 10);
        textView.setLayoutParams(lp);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final int size = linearFencesLayout.getChildCount();
                for (int i = 0; i < size; i++) {
                    AppCompatTextView text = (AppCompatTextView) linearFencesLayout.getChildAt(i);
                    text.setTextColor(ResourcesUtil.getColorFromResources(getContext(), R.color.text_fences));
                }
                final AppCompatTextView childView = (AppCompatTextView) linearFencesLayout.getChildAt(fencePosition);
                childView.setTextColor(ResourcesUtil.getColorFromResources(getContext(), R.color.home_color));
                final MultipleItemEntity entity = mAdapter.getItem(lastProjectIndex);
                if (entity != null) {
                    final Project project = entity.getField(MultipleFields.PROJECT);
                    final ArrayList<Fences> fences = project.getUserElecFences();
                    drawFences(fences.get(fencePosition));
                }
            }
        });
        return textView;
    }

    private void drawFences(final Fences fences) {
        baiduMap.clear();
        mPresenter.getSubordinateNumber(fences.getEFB_ID() + "", fences.getEFB_Type(), fences.getPMP_Type(), fences.getPMP_Times());
    }

    @Override
    public AttendancePresenter getPresenter() {
        return new AttendancePresenter(this);
    }

    @Override
    public void getFencesLatLngListSuccess(final WeakHashMap<String, Object> list, final int fencesType, final int fencesCount) {
        final int type = (int) list.get(SpKey.KEY_FENCES_TYPE);
        @SuppressWarnings("unchecked") final ArrayList<LatLng> fences = (ArrayList<LatLng>) list.get(SpKey.KEY_FENCES_LAT_LNG);
        if (fences != null && fences.size() > 0) {
            switch (type) {
                //画圆
                case 1:
                    final LatLng center = fences.get(fences.size() - 1);
                    final int radius = (int) list.get(SpKey.KEY_FENCES_RADIUS);
                    OverlayOptions circle = DrawOverlay.drawCircle(center,
                            radius);
                    if (circle != null) {
                        // 画圆
                        baiduMap.addOverlay(circle);
                        // 画圆心
                        baiduMap.addOverlay(MarkerOverlay
                                .builderPointByTypeFromBitmap(center, 0));
                        // 圆心居中
                        baiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(center, 15.0f));
                        setBottomText(fencesType, fencesCount);
                    } else {
                        showErrorDialog();
                    }
                    break;
                case 3:
                    OverlayOptions polygon = DrawOverlay.drawPolygon(fences);
                    if (polygon != null) {
                        // 画多边形
                        baiduMap.addOverlay(polygon);
                        // 居中
                        baiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(fences.get(0), 15.0f));
                        setBottomText(fencesType, fencesCount);
                    } else {
                        showErrorDialog();
                    }
                    break;
                case 4:
                    OverlayOptions polyline = DrawOverlay.drawPolyline(fences);
                    if (polyline != null) {
                        // 画多边形
                        baiduMap.addOverlay(polyline);
                        // 居中
                        baiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(fences.get(0), 15.0f));
                        setBottomText(fencesType, fencesCount);
                    } else {
                        showErrorDialog();
                    }
                    break;
                default:
                    showErrorDialog();
                    break;
            }
        } else {
            showErrorDialog();
        }
    }

    @Override
    public void getFencesLatLngListFailed(int code, String msg) {
        showErrorDialog();
    }

    @Override
    public void showLoading(String str) {

    }

    @Override
    public void hideLoading() {

    }

    @SuppressLint("SetTextI18n")
    private void setBottomText(int fencesType, int fencesCount) {
        if (linearLayoutBottom != null) {
            linearLayoutBottom.setVisibility(View.VISIBLE);
        }
        if (textAttendanceRule != null) {
            switch (fencesType) {
                case 1:
                    textAttendanceRule.setText("规则：每周必须进一次");
                    break;
                case 2:
                    textAttendanceRule.setText("规则：每月必须进一次");
                    break;
                default:
                    textAttendanceRule.setText("规则：每天必须进一次");
                    break;
            }
        }
        if (textAttendanceCount != null) {
            if (fencesCount == 0) {
                textAttendanceCount.setText("次数：1");
            } else {
                textAttendanceCount.setText("次数：" + fencesCount);
            }
        }
    }

    private void showErrorDialog() {
        if (linearLayoutBottom != null) {
            linearLayoutBottom.setVisibility(View.GONE);
        }
        if (mDialogLoader != null) {
            mDialogLoader.showNormalHideCancel("提示", "未获取到围栏信息", new IDialogClickListener() {
                @Override
                public void onClick() {
                    mDialogLoader.clearDialog();
                }
            });
        }
    }
}
